package main

import (
	"fmt"

	"gorm.io/driver/postgres"
	"gorm.io/gen"
	"gorm.io/gorm"
)

func genMain() {
	// 数据库连接信息，需要根据实际情况修改
	//dsn := "user:password@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
	//db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	// if err != nil {
	// 	panic(err)
	// }
	db := getDb2()

	g := gen.NewGenerator(gen.Config{
		OutPath: "./dao",
		Mode:    gen.WithoutContext | gen.WithDefaultQuery | gen.WithQueryInterface,
	})

	g.UseDB(db)

	tables, err := db.Migrator().GetTables()
	if err != nil {
		panic("failed to fetch tables: " + err.Error())
	}
	fmt.Println("Tables:", tables)

	for _, table := range tables {
		columns, err := db.Migrator().ColumnTypes(table)
		if err != nil {
			// panic("failed to fetch columns for table " + table + ": " + err.Error())
			fmt.Printf("Error fetching columns for table %s: %v\n", table, err)
			continue // 跳过有问题的表，继续处理其他表
		}
		fmt.Printf("Table: %s, Columns: %v\n", table, columns)
	}

	// 自动生成所有表的模型
	// lab_user lab_project
	// g.GenerateModel("lab_user")
	g.ApplyBasic(g.GenerateAllTable()...)

	// 生成代码
	g.Execute()
}

func getDb2() *gorm.DB {

	//dsn := "host=localhost user=postgres password=1234qwer dbname=lab port=5436 sslmode=disable TimeZone=Asia/Shanghai"

	dsn := "host=localhost user=lab password=1234qwer dbname=go-test port=5436 sslmode=disable TimeZone=Asia/Shanghai"
	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}

	return db
}
